package we.core.handlers;

import java.nio.channels.SocketChannel;

import java.util.HashMap;
import java.util.Map;

import we.common.CCommonHandler;

import we.core.bean.CDataContainer;
import we.core.bean.CRoom;
import we.core.bean.CUser;

import we.extension.CSystemEvent;

import org.json.JSONException;
import org.json.JSONObject;


public class CJoinRoomHandler extends CAbstractCoreHandler {
    public CJoinRoomHandler() {
    }

    public int handleEvent(SocketChannel channel, JSONObject data) {
        String username;
        int toRoomId;
        int fromRoomId;
        try {
            username = data.getString("username");
            toRoomId = data.getInt("toRoomId");
            fromRoomId = data.getInt("fromRoomId");
            String password = data.getString("password");
            CUser u = null;
            if ((u = CDataContainer.instance().getUser(username)) != null) {
                CRoom fromRoom = CDataContainer.instance().getRoom(fromRoomId);
                if (fromRoom != null)
                    fromRoom.removeUser(u.username);
                CRoom toRoom = CDataContainer.instance().getRoom(toRoomId);
                if (toRoom.getPassword().equals(password)) {
                    toRoom.addUser(u);
                    u.roomId = toRoomId;
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("eventName",
                               CSystemEvent.SystemEventType.JOIN_ROOM);
                    params.put("user", u);
                    params.put("toRoom", toRoom);
                    CSystemEvent se = new CSystemEvent(this, params);
                    dispatchSystemEvent(se);
                    return 0; // join room Ok.
                }
            }
        } catch (JSONException e) {
            CCommonHandler.writeErrLog(e);
            // TODO
        }
        return -1; // join room false

    }
}
